package com.wx.forum.interceptor;

import com.wx.forum.contant.Contants;
import com.wx.forum.service.IAuthService;
import com.wx.forum.utils.JwtUtil;
import com.wx.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${forum.login.url}")
    private String url;
    @Autowired
    private IAuthService authService;
    /**
     * 前置处理，对请求的预处理
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验token
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        if(StringUtil.isEmpty(token)){
            response.setStatus(401);
            log.warn("token == null");
            return false;
        }
        //从redis中拿token
        Long userId = JwtUtil.getIdByToken(token);
        if(userId == null){
            response.setStatus(401);
            log.warn("userId == null");
            return false;
        }
        String redisToken = authService.getToken(userId);
        if(redisToken == null || !token.equals(redisToken)){
            response.setStatus(401);
            log.warn("token无效");
            return false;
        }

        //验证通过
        return true;
    }
}
